<!--
 * @Author: 107w 8801453+lu-shangru@user.noreply.gitee.com
 * @Date: 2023-05-26 12:00:47
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-04-23 16:05:59
 * @Description:
 *
 * Copyright (c) 2023 by 107w, All Rights Reserved.
-->
<template>
  <div class="wrap">
    <div class="container">
      <div class="title">
        <el-row>
          <div class="vertical" />
          <span>修改密码</span>
        </el-row>
        <el-divider />
      </div>
      <div class="content">
        <el-form
          ref="passwdForm"
          :model="passwdForm"
          :rules="rules"
          label-width="200px"
          class="passwdForm"
        >
          <el-form-item label="新密码" prop="newPass">
            <el-input
              id="newPass"
              v-model="passwdForm.newPass"
              placeholder="请输入新密码"
              :readonly="readonly.newPass"
              auto-complete="off"
              type="password"
              style="width: 300px"
              show-password
              @click.native="passwdFocus('newPass')"
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="repassword">
            <el-input
              id="repassword"
              v-model="passwdForm.repassword"
              placeholder="请输入新密码"
              :readonly="readonly.repassword"
              auto-complete="off"
              style="width: 300px"
              show-password
              @click.native="passwdFocus('repassword')"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="passwdEdit"
            >确认修改</el-button>
          </el-form-item>
        </el-form>
        <div class="passwdNotice" style="margin-left: 45px">
          <p>1. 建议密码8到16位，且不能出现空格</p>
          <p>2. 建议每周或者每月更改一次密码</p>
          <p>
            3. 建议密码组合不低于三种方式，大写英文+小写英文+数字+特殊符号。
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { passwdReset } from '@/api/userManage/users'
import { validatePassword } from '@/utils'
export default {
  name: 'Password',
  components: {},
  data() {
    return {
      passwdForm: {
        newPass: '',
        repassword: ''
      },
      readonly: {
        oldPass: true,
        newPass: true,
        repassword: true
      },
      rules: {
        newPass: [
          {
            required: true,
            message: '请输入新密码',
            trigger: ['blur', 'change']
          },
          { validator: validatePassword }
        ],
        repassword: [
          {
            required: true,
            message: '请再次输入新密码',
            trigger: ['blur', 'change']
          },
          { validator: this.validateRepassword }
        ]
      },
      password: '',
      form: {
        userName: '',
        password: ''
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  async created() {},
  methods: {
    // 排他去除readonly属性，解决浏览器密码自动填充
    passwdFocus(pass) {
      for (const iterator in this.readonly) {
        this.readonly[iterator] = false
      }
      this.readonly[pass] = false
    },
    validateRepassword(rule, value, callback) {
      if (this.passwdForm.newPass !== this.passwdForm.repassword) {
        callback(new Error('两次密码输入不一致!'))
      }
      callback()
    },
    // 修改密码接口
    passwdEdit() {
      this.$refs['passwdForm'].validate(async(valid) => {
        if (valid) {
          this.passwdReset(this.passwdForm.repassword)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // type="password" => type="text"防止浏览器自动填入密码的解决方案
    inputPassword(e) {
      const value = e.target.value // 当前的值
      const oldVal = this.form.password // 之前的值
      let passwordShow = '' // 当前输入下需要显示的值，及n个*的字符串
      let text = '' // 当前input事件输入的值，如果是删除就没有值
      // 当前input指针的位置，不一定是在最后
      const startPoint = e.target.selectionStart
      // const endPoint = e.target.selectionEnd
      if (!value) {
        this.form.password = ''
        this.password = ''
        return
      }
      let leftNum = 0 // 输入后左边保留多少
      let rightNum = 0 // 输入后右边保留多少
      let isLeft = true
      for (let i = 0; i < value.length; i++) {
        passwordShow += '•'
        if (value[i] === '•') {
          if (isLeft) {
            leftNum++
          } else {
            rightNum++
          }
          continue
        }
        text += value[i]
        isLeft = false
      }

      if (text) {
        this.form.password =
          oldVal.slice(0, leftNum) +
          text +
          oldVal.slice(oldVal.length - rightNum)
      } else {
        // if (startPoint >= value.length) {
        this.form.password =
          oldVal.slice(0, startPoint) +
          oldVal.slice(oldVal.length - leftNum - rightNum + startPoint)
        // } else {
        //   this.form.password =
        //     oldVal.slice(0, startPoint) +
        //     oldVal.slice(oldVal.length - leftNum - rightNum + endPoint);
        // }
      }
      this.password = passwordShow
      this.$nextTick(() => {
        e.target.setSelectionRange(startPoint, startPoint)
      })
    },
    async passwdReset(passWord) {
      try {
        const params = {
          id: this.userInfo.id,
          passWord: passWord
        }
        const res = await passwdReset(params)
        if (res.success) {
          this.$message.success(
            `【${this.userInfo.userName}】用户的密码修改成功`
          )
          this.$store.dispatch('user/logout')
          this.$router.push('/login')
        } else {
          return false
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
  .container {
    padding: 15px;
    border-radius: 6px;
    min-height: 100%;
    background-color: #fff;
    ::v-deep .top_tabs {
      .el-tabs__nav-wrap {
        padding: 10px 20px;
        padding-bottom: 0;
        line-height: 16px;
      }
      .el-tabs__nav-wrap::after {
        height: 1px;
      }
    }
  }
}
.content {
  margin-top: 20px;
  display: flex;
  .passwdForm {
    width: 540px;
    flex-shrink: 0;
  }
  .passwdNotice {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    margin-top: 0px;
    p {
      margin-bottom: 22px;
    }
  }
}
.vertical {
  display: inline-block;
  width: 3px;
  height: 18px;
  border-radius: 2px;
  margin-right: 6px;
  background-color: #409dfe;
  vertical-align: bottom;
}
.el-divider--horizontal {
  margin: 10px 0 0 0;
}
.passwdNotice {
  margin-top: 30px;
  // margin-left: 45px;
  font-size: 14px;
  color: #999;
  p {
    margin: 5px 0;
  }
}
</style>
